/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dragoncon.dcsched.io;

import com.dragoncon.dcsched.R;
import com.dragoncon.dcsched.provider.ScheduleContract;
import com.dragoncon.dcsched.provider.ScheduleContract.Rooms;
import com.dragoncon.dcsched.provider.ScheduleContract.SyncColumns;
import com.dragoncon.dcsched.util.Lists;
import com.dragoncon.dcsched.util.SpreadsheetEntry;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.net.Uri;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;

import static com.dragoncon.dcsched.util.ParserUtils.AtomTags.ENTRY;
import static com.dragoncon.dcsched.util.ParserUtils.queryItemUpdated;
import static com.dragoncon.dcsched.util.ParserUtils.sanitizeId;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;

/**
 * Handle a remote {@link XmlPullParser} that defines a set of {@link Rooms}
 * entries. Assumes that the remote source is a Google Spreadsheet.
 */
public class RemoteRoomsHandler extends XmlHandler {
    private static final String TAG = "RoomsHandler";

    public RemoteRoomsHandler() {
        super(ScheduleContract.CONTENT_AUTHORITY);
    }

    /** {@inheritDoc} */
    @Override
    public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver)
            throws XmlPullParserException, IOException {
        final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

        int type;
        while ((type = parser.next()) != END_DOCUMENT) {
            if (type == START_TAG && ENTRY.equals(parser.getName())) {
                // Process single spreadsheet row at a time
                final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser);

                final String roomId = sanitizeId(entry.get(Columns.ROOM_ID), true);
                final Uri roomUri = Rooms.buildRoomUri(roomId);

                // Check for existing details, only update when changed
                final long localUpdated = queryItemUpdated(roomUri, resolver);
                final long serverUpdated = entry.getUpdated();
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "found room " + entry.toString());
                    Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
                }
                if (localUpdated >= serverUpdated) continue;

                // Clear any existing values for this room, treating the
                // incoming details as authoritative.
                batch.add(ContentProviderOperation.newDelete(roomUri).build());

                final ContentProviderOperation.Builder builder = ContentProviderOperation
                        .newInsert(Rooms.CONTENT_URI);

                builder.withValue(SyncColumns.UPDATED, serverUpdated);
                builder.withValue(Rooms.ROOM_ID, roomId);
                builder.withValue(Rooms.ROOM_NAME, entry.get(Columns.ROOM_NAME));
                builder.withValue(Rooms.ROOM_BUILDING, entry.get(Columns.ROOM_BUILDING));
                builder.withValue(Rooms.ROOM_FLOOR, entry.get(Columns.ROOM_FLOOR));

		final String xStr = entry.get(Columns.ROOM_POSITION_X);
		final String yStr = entry.get(Columns.ROOM_POSITION_Y);
		
		float x = 0;
		float y = 0;
		if(xStr != null && yStr != null) {
		    // Some rooms may have no set position
		    try {
			x = Float.parseFloat(xStr);
			y = Float.parseFloat(yStr);
		    } catch (NumberFormatException e) {
			Log.w(TAG, "Invalid room position: "+e);
		    }
		} else {
		    Log.w(TAG, "Room "+entry.get(Columns.ROOM_NAME)+" is missing position: "+xStr+","+yStr);
		}
		builder.withValue(Rooms.ROOM_POSITION_X, x);
		builder.withValue(Rooms.ROOM_POSITION_Y, y);

                // Normal room details ready, write to provider
                batch.add(builder.build());
            }
        }

        return batch;
    }

    /** Columns coming from remote spreadsheet. */
    private interface Columns {
        String ROOM_ID = "roomid";
        String ROOM_NAME = "roomname";
        String ROOM_BUILDING = "roombuilding";
        String ROOM_FLOOR = "roomfloor";
        String ROOM_POSITION_X = "roompositionx";
        String ROOM_POSITION_Y = "roompositiony";

        // room_id: 22
        // room_name: Intl. C
        // room_building: Weston
        // room_floor: Lobby
        // room_position_x: 252.6
        // room_position_y: 486

    }
}
